package com.digital.smartgrow.common.filter;


import com.alibaba.fastjson.JSON;
import com.digital.smartgrow.common.advice.Result;
import com.digital.smartgrow.common.advice.ReturnCode;
import com.digital.smartgrow.entity.datacenter.Teacher;
import com.github.benmanes.caffeine.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(2)
@WebFilter(filterName = "LoginFilter", urlPatterns = "/api/*")
public class LoginFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Cache<String, Teacher> teacherCache;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

//    @Bean("LoginFilterBean")
//    public FilterRegistrationBean setBean() {
//        FilterRegistrationBean bean = new FilterRegistrationBean<>();
//        bean.setFilter(new LoginFilter());
//        bean.addUrlPatterns("/web/*");
//        bean.setName("LoginFilter");
//        bean.setOrder(2);
//        return bean;
//    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (request.getRequestURI().contains("favicon.ico")) return;//过滤无效请求
        ServletContext sc = request.getSession().getServletContext();
        AbstractApplicationContext cxt = (AbstractApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);

        /**
         * 验证具体的token规则
         */
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("token");//header方式
        }
        //判断是否拦截
        String requestURI = request.getRequestURI();
        long count = 0;
        if (count == 0) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setContentType("application/json;charset=utf-8");
            if (token == null) {
                servletResponse.getWriter().write(JSON.toJSONString(Result.fail(ReturnCode.INVALID_TOKEN.getCode(),"token不能为空")));
                return;
            }
            Teacher teacher = teacherCache.getIfPresent(token);
            if (teacher == null) {
//            if (!"0123456789abcdef".equals(token)) {
                servletResponse.getWriter().write(JSON.toJSONString(Result.fail(ReturnCode.INVALID_TOKEN.getCode(),"token验证失败")));
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
